package modules.loan.service.impl;

import java.math.BigDecimal;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import luxing.common.service.impl.CommonServiceImpl;
import modules.loan.entity.LoanContract;
import modules.loan.entity.Loan;
import modules.loan.entity.LoanRepayment;
import modules.loan.service.LoanRepaymentService;

/**
 * 
 * @author zzc
 *
 */
@Service("loanRepaymentService")
@Transactional
public class LoanRepaymentServiceImpl extends CommonServiceImpl implements LoanRepaymentService {

	public void doVoid(LoanRepayment loanRepayment) {
		// 还款记录作废
		super.saveOrUpdate(loanRepayment);
		// 借款
		Loan loan = loanRepayment.getLoan();
		loan.setRealPrincipal(loan.getRealPrincipal().subtract(loanRepayment.getPrincipal()));
		loan.setRealInterest(loan.getRealInterest().subtract(loanRepayment.getInterest()));
		loan.setRealTotalAmount(loan.getRealTotalAmount().subtract(loanRepayment.getTotalAmount()));
		if (loan.getRealTotalAmount().compareTo(loan.getTotalAmount()) >= 0) {
			// 如果实还总额大于应还总额,则尚欠金额为0,状态为已还清
			loan.setOweAmount(new BigDecimal(0));
			loan.setStatus(Loan.STATUS_YES);
		} else {
			loan.setOweAmount(loan.getTotalAmount().subtract(loan.getRealTotalAmount()));
			if (loan.getRealTotalAmount().compareTo(new BigDecimal(0)) == 0) {
				// 如果实还总额等于0
				loan.setStatus(Loan.STATUS_NO);
			} else {
				loan.setStatus(Loan.STATUS_ING);
			}
		}
		super.saveOrUpdate(loan);
		// 贷款合同
		LoanContract loanContract = loan.getLoanContract();
		BigDecimal realPrincipal = new BigDecimal(0);
		BigDecimal realInterest = new BigDecimal(0);
		BigDecimal realTotalAmount = new BigDecimal(0);
		BigDecimal oweAmount = new BigDecimal(0);
		String status = "";
		for (Loan entity : loanContract.getLoanList()) {
			realPrincipal = realPrincipal.add(entity.getRealPrincipal());
			realInterest = realInterest.add(entity.getRealInterest());
			realTotalAmount = realTotalAmount.add(entity.getRealTotalAmount());
			oweAmount = oweAmount.add(entity.getOweAmount());
			status += entity.getStatus();
		}
		loanContract.setRealPrincipal(realPrincipal);
		loanContract.setRealInterest(realInterest);
		loanContract.setRealTotalAmount(realTotalAmount);
		loanContract.setOweAmount(oweAmount);
		if (!status.contains("0") && !status.contains("1")) {
			loanContract.setStatus(LoanContract.STATUS_YES);
		} else if (status.contains("1")) {
			loanContract.setStatus(LoanContract.STATUS_ING);
		} else if (!status.contains("1") && !status.contains("2")) {
			loanContract.setStatus(LoanContract.STATUS_NO);
		}
		super.saveOrUpdate(loanContract);
	}
}
